package go_redisson

import (
	"github.com/gomodule/redigo/redis"
	"go-redisson/api"
	"go-redisson/logger"
	"log"
	"os"
	"time"
)

type Redisson struct {
	config   Config           // Redis 配置
	Delegate *redis.Pool      // Redis 连接池
	l        logger.Interface // 日志接口
	execute  CommandExecutor  // 命令执行器
}

func (redisson *Redisson) Create(c Config) *Redisson {
	// 1. 初始化配置
	redisson.config = c

	// 2. 初始化 log
	l := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
		Colorful: true,
		LogLevel: logger.Info,
	})

	// 3. 单服务节点操作
	if !c.SingleServerConfig.IsEmpty() {
		l.Info("start init single server redisson...")

		// 4， 处理默认值
		handleDefaultParam(&c)

		// 5. 初始化连接池
		singleConfig := c.SingleServerConfig
		redisson.Delegate = &redis.Pool{
			MaxIdle:     singleConfig.MaxIdle,
			MaxActive:   singleConfig.MaxActive,
			IdleTimeout: singleConfig.IdleTimeout,
			Wait:        singleConfig.Wait,
			Dial: func() (redis.Conn, error) {
				con, err := redis.Dial(
					singleConfig.Protocol,
					singleConfig.address,
					redis.DialPassword(singleConfig.Password),
					redis.DialDatabase(singleConfig.database),
					redis.DialConnectTimeout(singleConfig.ConnectTimeout),
					redis.DialReadTimeout(singleConfig.ReadTimeout),
					redis.DialWriteTimeout(singleConfig.WriteTimeout),
				)
				if err != nil {
					l.Error("redisson initialization error， %s", err)
					return nil, err
				}
				return con, nil
			},
		}

		// 6. 初始化 CommandExecute
		redisson.execute = &CommandAsyncExecutor{}
	}
	return redisson
}

// 处理默认参数
func handleDefaultParam(c *Config) Config {
	singleConfig := &c.SingleServerConfig

	// 默认空闲数
	if singleConfig.MaxIdle == 0 {
		singleConfig.MaxIdle = DefaultMaxIdle
	}

	// 默认最大连接数
	if singleConfig.MaxActive == 0 {
		singleConfig.MaxActive = DefaultMaxActive
	}

	// 空闲连接最大时间
	if singleConfig.IdleTimeout == 0 {
		singleConfig.IdleTimeout = DefaultMaxIdleTimeout * time.Second
	}

	// 连接超时
	if singleConfig.ConnectTimeout == 0 {
		singleConfig.ConnectTimeout = DefaultConnectTimeout * time.Second
	}

	// 读超时
	if singleConfig.ReadTimeout == 0 {
		singleConfig.ReadTimeout = DefaultReadTimeout * time.Second
	}

	// 写超时
	if singleConfig.WriteTimeout == 0 {
		singleConfig.WriteTimeout = DefaultWriteTimeout * time.Second
	}

	// 默认协议
	if singleConfig.Protocol == "" {
		singleConfig.Protocol = DefaultProtocol
	}
	return *c
}

// -----------------------------------------以下为 Redisson Client 实现-------------------------------------------------

func (redisson *Redisson) GetBucket() api.RBucket {
	return &api.RedissonBucket{}
}

func (redisson *Redisson) GetLock() api.RBucket {
	return nil
}
